package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayConfig;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum;
import com.gzhryc.shared_device.common.payment.services.WXPayConfigService;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.business.EFuncModelShowState;
import com.gzhryc.shared_device.oem.code.config.dao.db.AgreementDocument;
import com.gzhryc.shared_device.oem.code.config.dao.db.FuncModel;
import com.gzhryc.shared_device.oem.code.config.dao.enums.FuncModelEnum;
import com.gzhryc.shared_device.oem.code.config.services.AgreementDocumentService;
import com.gzhryc.shared_device.oem.code.config.services.FuncModelService;
import com.gzhryc.shared_device.oem.code.place.dao.db.ClerkFuncModel;
import com.gzhryc.shared_device.oem.code.place.dao.enums.ClerkFuncModelEnum;
import com.gzhryc.shared_device.oem.code.place.services.ClerkFuncModelService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.AppConfigResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.FuncModelChangeRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.AgentBusinessTypeListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.AgentBusinessTypeListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.AgreementDocumentInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.AgreementDocumentInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.FuncModelListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.config.FuncModelListResponse;

public class ConfigController {

    static Logger log = Logger.getLogger(ConfigController.class);

    @Route(value = "/agent/api/v1/config/business_type/role_type/list.data")
    public AgentBusinessTypeListResponse businessTypeList(HttpServletRequest request) {
    	AgentBusinessTypeListResponse apiResp = new AgentBusinessTypeListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	AgentBusinessTypeListRequest apiReq = WebUtils.getJsonRequest(request, AgentBusinessTypeListRequest.class);
        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
        if (loginUser != null) {
        	if (ERoleType.Agent.index().equals(loginUser.getRoleType())) {
        		if(apiReq.getBody().getUserId() != null) {
        			List<AgentRelationBusinessConfig> businessConfigList = AgentRelationBusinessConfigService.self()
        					.findByUserKeys(loginUser.getId(), apiReq.getBody().getUserId());
            		if(businessConfigList != null && businessConfigList.size() > 0) {
            			apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
        				apiResp.getBody().setItems(new ArrayList<AgentBusinessTypeListResponse.Item>());
	        			for(AgentRelationBusinessConfig busiConfig : businessConfigList) {
	        				AgentBusinessTypeListResponse.Item item = new AgentBusinessTypeListResponse.Item();
	        				item.setBusinessType(busiConfig.getBusinessType());
	        				item.setBusinessTypeName(busiConfig.getBusinessTypeName());
	        				item.setIncomeRatio(busiConfig.getIncomeRatio());
	        				item.setEditFeeState(busiConfig.getEditFeeState());
	        				apiResp.getBody().getItems().add(item);
	        			}
            		}
        		}else {
        			List<AgentBusinessConfig> businessConfigList = AgentBusinessConfigService.self().findByUserId(loginUser.getId());
        			if(businessConfigList != null && businessConfigList.size() > 0) {
        				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
        				apiResp.getBody().setItems(new ArrayList<AgentBusinessTypeListResponse.Item>());
	        			for(AgentBusinessConfig busiConfig : businessConfigList) {
	        				AgentBusinessTypeListResponse.Item item = new AgentBusinessTypeListResponse.Item();
	        				item.setBusinessType(busiConfig.getBusinessType());
	        				item.setBusinessTypeName(busiConfig.getBusinessTypeName());
	        				apiResp.getBody().getItems().add(item);
	        			}
        			}
        		}
        	}
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/config/func_model/list.data")
    public FuncModelListResponse funcModelList(HttpServletRequest request) {
        FuncModelListResponse apiResp = new FuncModelListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
        if (loginUser != null) {
        	List<FuncModelListResponse.Item> items = new ArrayList<>();
            if (ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                List<FuncModel> data = FuncModelService.self().findByType(loginUser.getRoleType());
                if (data != null && data.size() > 0) {
                    List<AgentFuncModel> agentFuncModelList = AgentFuncModelService.self().findJoinByUserId(loginUser.getId());

                    for (FuncModel funcModel : data) {
                        if (FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
                            FuncModelListResponse.Item item = new FuncModelListResponse.Item();
                            item.setId(funcModel.getId());
                            item.setName(funcModel.getName());
                            item.setType(1);	//默认功能模块
                            item.setIconImg(funcModel.getIconUrl());
                            item.setUrl(funcModel.getUrl());
                            item.setHomeShow(EFuncModelShowState.HomeShow.index());     //默认的功能模块，默认首页显示
                            if (agentFuncModelList != null && agentFuncModelList.size() > 0) {
                                for (AgentFuncModel agentFuncModel : agentFuncModelList) {
                                    if (agentFuncModel.getFuncModelId().equals(funcModel.getId())) {
                                        item.setHomeShow(agentFuncModel.getState());
                                        break;
                                    }
                                }
                            }
                            items.add(item);
                        } else {
                            //选配的功能模块
                            int flag = 0;
                            AgentFuncModel temp = null;
                            if (agentFuncModelList != null && agentFuncModelList.size() > 0) {
                                for (AgentFuncModel agentFuncModel : agentFuncModelList) {
                                    if (agentFuncModel.getFuncModelId().equals(funcModel.getId())) {
                                        temp = agentFuncModel;
                                        flag = 1;
                                        break;
                                    }
                                }
                            }
                            if (flag == 1) {
                                FuncModelListResponse.Item item = new FuncModelListResponse.Item();
                                item.setId(funcModel.getId());
                                item.setName(funcModel.getName());
                                item.setType(1);	//默认功能模块
                                item.setIconImg(funcModel.getIconUrl());
                                item.setUrl(funcModel.getUrl());
                                item.setHomeShow(EFuncModelShowState.Normal.index());
                                if (temp != null) {
                                    item.setHomeShow(temp.getState());
                                }
                                items.add(item);
                            }
                        }
                    }
                }
            }else if(ERoleType.Clerk.index().equals(loginUser.getRoleType())) {
            	List<ClerkFuncModel> clerkFuncModelList = ClerkFuncModelService.self().findJoinByUserKeys(loginUser.getId(), loginUser.getParentId());
            	if(clerkFuncModelList != null && clerkFuncModelList.size() > 0) {
            		for(ClerkFuncModel clerkFuncModel : clerkFuncModelList) {
            			if(ClerkFuncModelEnum.State.Open.index().equals(clerkFuncModel.getState())) {
            				FuncModel funcModel = clerkFuncModel.getFuncModel();
            				
            				FuncModelListResponse.Item item = new FuncModelListResponse.Item();
                            item.setId(funcModel.getId());
                            item.setName(funcModel.getName());
                            item.setType(1);	//默认功能模块
                            item.setIconImg(funcModel.getIconUrl());
                            item.setUrl(funcModel.getUrl());
                            item.setHomeShow(EFuncModelShowState.HomeShow.index());
                            items.add(item);
            			}
            		}
            	}
            } else {
            	 List<FuncModel> data = FuncModelService.self().findByType(loginUser.getRoleType());
                 if (data != null && data.size() > 0) {
                	 List<AgentRelationFuncModel> funcModelList = AgentRelationFuncModelService.self().findJoinByUserKeys(loginUser.getParentId(), loginUser.getId());
                	 for (FuncModel funcModel : data) {
                		 if (FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
                			 boolean flag = true;
                			 if (funcModelList != null && funcModelList.size() > 0) {
                                 for (AgentRelationFuncModel relationFuncModel : funcModelList) {
                                     if (relationFuncModel.getFuncModelId().equals(funcModel.getId())) {
                                         if(AgentRelationFuncModelEnum.State.Close.index().equals(relationFuncModel.getState())){
                                        	 flag = false;
                                         }
                                         break;
                                     }
                                 }
                             }
                			 if(flag) {
                				 FuncModelListResponse.Item item = new FuncModelListResponse.Item();
                                 item.setId(funcModel.getId());
                                 item.setName(funcModel.getName());
                                 item.setType(1);	//默认功能模块
                                 item.setIconImg(funcModel.getIconUrl());
                                 item.setUrl(funcModel.getUrl());
                                 item.setHomeShow(EFuncModelShowState.HomeShow.index());
                                 items.add(item);
                			 }
                		 }else {
                			 boolean flag = false;
                			 if (funcModelList != null && funcModelList.size() > 0) {
                                 for (AgentRelationFuncModel relationFuncModel : funcModelList) {
                                     if (relationFuncModel.getFuncModelId().equals(funcModel.getId())) {
                                         if(AgentRelationFuncModelEnum.State.Open.index().equals(relationFuncModel.getState())){
                                        	 flag = true;
                                         }
                                         break;
                                     }
                                 }
                             }
                			 
                			 if(flag) {
                				 FuncModelListResponse.Item item = new FuncModelListResponse.Item();
                                 item.setId(funcModel.getId());
                                 item.setName(funcModel.getName());
                                 item.setType(1);	//默认功能模块
                                 item.setIconImg(funcModel.getIconUrl());
                                 item.setUrl(funcModel.getUrl());
                                 item.setHomeShow(EFuncModelShowState.HomeShow.index());
                                 items.add(item);
                			 }
                		 }
                	 }
                 }
            }

            if (items.size() > 0) {
                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                apiResp.getBody().setItems(items);
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/config/func_model/state/update.do")
    public DefaultAPIResponse updateFuncModelState(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        FuncModelChangeRequest apiReq = WebUtils.getJsonRequest(request, FuncModelChangeRequest.class);
        if (apiReq != null && apiReq.getBody().getId() != null && apiReq.getBody().getState() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                if (StringTools.isBlank(EFuncModelShowState.note(apiReq.getBody().getState()))) {
                    apiResp.setMsg("未知的状态");
                    return apiResp;
                }

                if(ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                    if (AgentFuncModelService.self().updateState(loginUser.getId(), apiReq.getBody().getId(), apiReq.getBody().getState())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                }else if(ERoleType.Merchant.index().equals(loginUser.getRoleType()) || ERoleType.Partner.index().equals(loginUser.getRoleType())) {
                    if (AgentRelationFuncModelService.self().updateState(loginUser.getParentId(),loginUser.getId(),apiReq.getBody().getId()
                            ,apiReq.getBody().getState())){
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                }
            }
        }
        return apiResp;
    }

    /**
     * 获取合伙人全部可用功能模块
     * @param request
     * @return
     */
    @Route(value = "/agent/api/v1/config/func_model/role_type/list.data")
    public FuncModelListResponse funcModelStaffList(HttpServletRequest request) {
        FuncModelListResponse apiResp = new FuncModelListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        FuncModelListRequest apiReq = WebUtils.getJsonRequest(request, FuncModelListRequest.class);
        if (apiReq != null && apiReq.getBody().getType() != null) {
	        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
	        if (loginUser != null) {
	            List<FuncModelListResponse.Item> items = new ArrayList<>();
	            if (ERoleType.Agent.index().equals(loginUser.getRoleType())) {
	            	if(ERoleType.Partner.index().equals(apiReq.getBody().getType()) 
	            			|| ERoleType.Merchant.index().equals(apiReq.getBody().getType())) {
		            	//获取功能模块
		                List<FuncModel> data = FuncModelService.self().findByType(apiReq.getBody().getType());
		                if (data != null && data.size() > 0) {
		                	List<AgentRelationFuncModel> arFuncModelList = null;
		                	if(apiReq.getBody().getUserId() != null) {
		                		arFuncModelList = AgentRelationFuncModelService.self().findJoinByUserKeys(loginUser.getId(),apiReq.getBody().getUserId());
		                	}
		                	
		                    for (FuncModel funcModel : data) {
		                    	FuncModelListResponse.Item item = new FuncModelListResponse.Item();
		                        item.setId(funcModel.getId());
		                        item.setName(funcModel.getName());
		                        item.setType(1);	//默认功能模块
		                        item.setIconImg(funcModel.getIconUrl());
		                        item.setUrl(funcModel.getUrl());
		                        item.setHomeShow(EFuncModelShowState.HomeShow.index());     //默认的功能模块，默认首页显示
		                        if (FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
		                        	item.setState(AgentRelationFuncModelEnum.State.Open.index());		//2代表启用
		                        }else {
		                        	item.setState(AgentRelationFuncModelEnum.State.Close.index());		//1代表未启用
		                        }
		                        if(arFuncModelList != null && arFuncModelList.size() > 0) {
		                        	for(AgentRelationFuncModel arFuncModel :arFuncModelList) {
		                        		if(arFuncModel.getFuncModelId().equals(funcModel.getId())) {
		                        			item.setState(arFuncModel.getState());	
		                        			break;
		                        		}
		                        	}
		                        }
		                        items.add(item);
		                    }
		            	}
		                
		                AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),apiReq.getBody().getUserId());
		                if(agentRelation != null) {
		                	//根据角色获取权限
			                for(AgentRelationEnum.PowerType powerType : AgentRelationEnum.PowerType.values()) {
			                	if(powerType.roleType().equals(apiReq.getBody().getType())) {
				                	FuncModelListResponse.Item item = new FuncModelListResponse.Item();
				                	item.setCode(powerType.name());
				                	item.setName(powerType.note());
				                    item.setType(2);	//管理权限
				                    item.setState(1);
				                    if(AgentRelationEnum.PowerType.CanUndeployDevice.name().equals(powerType.name())) {
				                    	if(agentRelation.getCanUndeployDevice() == 1) {
				                    		item.setState(2);
				                    	}
				                    }
				                    items.add(item);
			                	}
			                }
		                }
		                if(items.size() > 0) {
		                	apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
		                	apiResp.getBody().setItems(items);
		                }
		            }
	            }else {
	            	apiResp.setCode(ClientAPICodeConstants.NOT_POWER, "无权限查看");
	            }
	        }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/agreement/info.data")
    public AgreementDocumentInfoResponse getAgreementDoc(HttpServletRequest request) {
    	AgreementDocumentInfoResponse apiResp = new AgreementDocumentInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	AgreementDocumentInfoRequest apiReq = WebUtils.getJsonRequest(request, AgreementDocumentInfoRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getAppId()) && StringTools.isNotBlank(apiReq.getBody().getCode())) {
        	 AgreementDocument agreementDoc = AgreementDocumentService.self().getByKeys(apiReq.getBody().getCode(), apiReq.getBody().getAppId());
        	 if(agreementDoc != null) {
        		 apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
        		 apiResp.getBody().setTitle(agreementDoc.getTitle());
        		 apiResp.getBody().setContent(agreementDoc.getContent());
        	 }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/app/config.data")
    public AppConfigResponse getAppConfig() {
    	AppConfigResponse apiResp = new AppConfigResponse(ClientAPICodeConstants.SUCCESS, null);
    	apiResp.getBody().setResDomain(PropertyTools.get().getString("resDomain"));
    	//获取默认微信公众号
    	WXPayConfig wxpayConfig = WXPayConfigService.self().getDef(WXPayConfigEnum.AppType.wxgzh.index());
		if(wxpayConfig != null) {
			apiResp.getBody().setAppId(wxpayConfig.getAppId());
		}
		log.info("代理端配置返回：{{0}}", apiResp);
        return apiResp;
    }
}
